package com.cjx.stars.listener;

import cn.hutool.bloomfilter.BitSetBloomFilter;
import cn.hutool.bloomfilter.BloomFilter;
import cn.hutool.bloomfilter.BloomFilterUtil;
import cn.hutool.core.util.BooleanUtil;
import com.cjx.stars.pojo.table.Blog;
import com.cjx.stars.pojo.table.Team;
import com.cjx.stars.pojo.table.User;
import com.cjx.stars.properties.StarsProperties;
import com.cjx.stars.service.BlogService;
import com.cjx.stars.service.TeamService;
import com.cjx.stars.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.openxmlformats.schemas.drawingml.x2006.chart.STGapAmount;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

import static com.cjx.stars.constant.BloomFilterConstants.*;

/**
 * @author cjx
 * @description 程序启动时的配置
 * @createDate 2024/4/23 17:12
 **/
@Configuration
@Log4j2
public class StartupListener implements CommandLineRunner {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private BlogService blogService;
    @Resource
    private StarsProperties starsProperties;

    @Override
    public void run(String... args) throws Exception {
        //根据配置信息判断是否开启布隆过滤器
        if (starsProperties.isEnableBloomFilter()){
        //开启布隆过滤器计算初始化布隆过滤器的时间
            long start = System.currentTimeMillis();
            log.info("布隆过滤器开始初始化 !");
            this.initBloomFilter();
            long end = System.currentTimeMillis();
            log.info("布隆过滤器初始化完毕！耗时：{} 毫秒",end - start);
        }
    }

    /**
     * 初始化布隆过滤器
     * @return 布隆过滤器
     */
    @Bean
    public BloomFilter initBloomFilter() {
        //1.创建Hutool的布隆过滤器类
        BitSetBloomFilter bloomFilter = BloomFilterUtil.createBitSet(
                PRE_OPENED_MAXIMUM_INCLUSION_RECORD,
                EXPECTED_INCLUSION_RECORD,
                HASH_FUNCTION_NUMBER
        );
        //2.将数据库中的用户，博文，队伍相关信息加入到过滤器中
        List<User> userList = userService.list(null);
        for (User user : userList) {
            bloomFilter.add(USER_BLOOM_PREFIX + user.getUserId());
        }
        List<Team> teamList = teamService.list(null);
        for (Team team : teamList) {
            bloomFilter.add(TEAM_BLOOM_PREFIX + team.getId());
        }

        List<Blog> blogList = blogService.list(null);
        for (Blog blog : blogList) {
            bloomFilter.add(BLOG_BLOOM_PREFIX + blog.getId());
        }
        return bloomFilter;
    }
}
